using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RiceShop.Models;
using RiceShop.Services;
using RiceShop.Extensions;
using System;
using System.Text.Json;

namespace RiceShop.Controllers
{
    /// <summary>
    /// 购物车控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]

    public class CartController : ControllerBase
    {
        private readonly ICartService _cartService;
        private readonly IGoodService _goodService;

        public CartController(ICartService cartService, IGoodService goodService)
        {
            _cartService = cartService;
            _goodService = goodService;
        }

        /// <summary>
        /// 获取用户购物车列表
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<List<Cart>>> GetCart()
        {
            try
            {
                var userId = User.GetUserId();
                var result = await _cartService.GetCartListAsync(userId);

                // 转换为前端需要的数据结构
                var cartList = result.Select(cart => new
                {
                    id = cart.Id,
                    spuId = cart.SpuId,
                    skuId = cart.SkuId,
                    title = cart.GoodTitle,
                    primaryImage = cart.Good?.PrimaryImage,
                    salePrice = cart.SalePrice,
                    quantity = cart.Quantity,
                    selected = cart.IsSelected,
                    specs = cart.SpecValues,  // 直接使用数据库中的规格值
                    linePrice = cart.LinePrice ?? 0,  // 确保有默认值
                    unit = cart.Unit ?? "件",  // 默认单位
                    code = cart.Code ?? ""  // 确保有默认值
                }).ToList();

                // 添加调试日志
                Console.WriteLine($"购物车列表数据: {JsonSerializer.Serialize(cartList)}");

                // 使用与其他接口一致的返回格式
                return Ok(new
                {
                    code = 200,
                    success = true,
                    data = cartList,
                    message = "获取购物车列表成功"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取购物车列表失败: {ex.Message}");
                return StatusCode(500, new
                {
                    code = 500,
                    success = false,
                    message = $"获取购物车失败: {ex.Message}"
                });
            }
        }

        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        /// <param name="request">购物车添加请求</param>
        [HttpPost("add")]
        public async Task<ActionResult> AddToCart([FromBody] AddCartRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ApiResponse<bool>.Error("无效的请求数据"));
                }

                var userId = User.GetUserId();

                // 检查商品是否存在
                var good = await _goodService.GetGoodByIdAsync(request.SpuId);
                if (good == null)
                {
                    return NotFound(ApiResponse<bool>.Error("商品不存在"));
                }

                // 创建购物车项
                var cart = new Cart
                {
                    SpuId = request.SpuId,
                    Quantity = request.Quantity,
                    GoodTitle = good.Title
                };

                // 判断是否是多规格商品
                if (good.OpenSpec == 1)  // 使用OpenSpec字段���断是否多规格
                {
                    // 多规格商品
                    if (request.SkuId <= 0)
                    {
                        return BadRequest(ApiResponse<bool>.Error("多规格商品必须选择规格"));
                    }

                    // 验证SKU是否属于该商品
                    var sku = await _goodService.GetSkuByIdAsync(request.SkuId);
                    if (sku == null || sku.SpuId != request.SpuId)
                    {
                        return BadRequest(ApiResponse<bool>.Error("无效的商品规格"));
                    }

                    cart.SkuId = request.SkuId;
                    cart.SalePrice = sku.SalePrice;
                    cart.SpecValues = sku.SpecValues;
                    cart.StockQuantity = sku.Stock ?? 0;
                    cart.LinePrice = sku.LinePrice;
                    cart.Code = sku.Code;
                }
                else
                {
                    // 单规格商品
                    cart.SkuId = good.SpuId;  // 单规格商品使用SpuId作为SkuId
                    if (!good.SalePrice.HasValue)
                    {
                        return BadRequest(ApiResponse<bool>.Error("商品价格未设置"));
                    }
                    cart.SalePrice = good.SalePrice.Value;
                    cart.StockQuantity = good.SpuStockQuantity ?? 0;
                    cart.SpecValues = "单规格";
                    cart.LinePrice = good.LinePrice;
                    cart.Code = good.SpuNo;
                }

                // 检查库存
                if (cart.Quantity > cart.StockQuantity)
                {
                    return BadRequest(ApiResponse<bool>.Error("商品库存不足"));
                }

                // 添加到购物车
                var result = await _cartService.AddToCartAsync(userId, cart);
                if (!result)
                {
                    return BadRequest(ApiResponse<bool>.Error("添加购物车失败"));
                }

                try
                {
                    // 获取新添加的购物车项完整信息
                    var addedCart = await _cartService.GetCartItemAsync(userId, cart.SkuId);
                    var cartData = new
                    {
                        id = addedCart.Id,
                        spuId = addedCart.SpuId,
                        skuId = addedCart.SkuId,
                        title = addedCart.GoodTitle,
                        primaryImage = addedCart.Good?.PrimaryImage,
                        salePrice = addedCart.SalePrice,
                        quantity = addedCart.Quantity,
                        selected = addedCart.IsSelected,
                        specs = addedCart.SpecValues,
                        linePrice = addedCart.LinePrice,
                        unit = addedCart.Unit,
                        code = addedCart.Code
                    };

                    return Ok(ApiResponse<object>.Ok(cartData, "添加到购物车成功"));
                }
                catch (Exception)
                {
                    // 如果获取新添加的购物车项失败，至少返回基本信息
                    var basicCartData = new
                    {
                        spuId = cart.SpuId,
                        skuId = cart.SkuId,
                        title = cart.GoodTitle,
                        salePrice = cart.SalePrice,
                        quantity = cart.Quantity,
                        selected = cart.IsSelected,
                        specs = cart.SpecValues,
                        linePrice = cart.LinePrice,
                        code = cart.Code
                    };

                    return Ok(ApiResponse<object>.Ok(basicCartData, "添加到购物车成功，但获取详情失败"));
                }
            }
            catch (Exception)
            {
                return StatusCode(500, ApiResponse<bool>.Error("添加购物车失败"));
            }
        }

        /// <summary>
        /// 更新购物车品数量
        /// </summary>
        [HttpPut("update")]
        public async Task<ActionResult> UpdateQuantity([FromBody] UpdateCartRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ApiResponse<bool>.Error("无效的请求数据"));
                }

                var userId = User.GetUserId();
                var cart = new Cart
                {
                    Quantity = request.Quantity
                };

                var result = await _cartService.UpdateQuantityAsync(userId, request.CartId, cart);

                // 获取更新后的购物车项完整信息
                var updatedCart = await _cartService.GetCartItemAsync(userId, request.CartId);
                var cartData = new
                {
                    id = updatedCart.Id,
                    spuId = updatedCart.SpuId,
                    skuId = updatedCart.SkuId,
                    title = updatedCart.GoodTitle,
                    primaryImage = updatedCart.Good?.PrimaryImage,
                    salePrice = updatedCart.SalePrice,
                    quantity = updatedCart.Quantity,
                    selected = updatedCart.IsSelected,
                    specs = updatedCart.SpecValues,
                    linePrice = updatedCart.LinePrice,
                    unit = updatedCart.Unit,
                    code = updatedCart.Code
                };

                return Ok(ApiResponse<object>.Ok(cartData, "更新购物车成功"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.Error($"更新购物车失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 从购物车中删除商品
        /// </summary>
        /// <param name="cartId">购物车项ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete/{cartId}")]
        public async Task<ActionResult> DeleteCartItem(long cartId)
        {
            try
            {
                var userId = User.GetUserId();
                var result = await _cartService.DeleteCartItemAsync(userId, cartId);
                return Ok(ApiResponse<bool>.Ok(result, "删除购物车商品成功"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.Error($"删除购物车商品失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// 清空购物车
        /// </summary>
        /// <returns>清空结果</returns>
        [HttpDelete("clear")]
        public async Task<ActionResult> ClearCart()
        {
            try
            {
                var userId = User.GetUserId();
                await _cartService.ClearCartAsync(userId);
                return Ok(ApiResponse<bool>.Ok(true, "清空购物车成功"));
            }
            catch (Exception ex)
            {
                return StatusCode(500, ApiResponse<bool>.Error($"清空购物车失败: {ex.Message}"));
            }
        }
    }

    /// <summary>
    /// 添加购物车请求模型
    /// </summary>
    public class AddCartRequest
    {
        /// <summary>
        /// 商品SPU ID
        /// </summary>
        public long SpuId { get; set; }

        /// <summary>
        /// SKU ID（多规格商品必填）
        /// </summary>
        public long SkuId { get; set; }

        /// <summary>
        /// 数量
        /// </summary>
        public int Quantity { get; set; }
    }

    /// <summary>
    /// 更新购物车请求模型
    /// </summary>
    public class UpdateCartRequest
    {
        /// <summary>
        /// 购物车ID
        /// </summary>
        public long CartId { get; set; }

        /// <summary>
        /// 数量
        /// </summary>
        public int Quantity { get; set; }
    }
}